package com.santu.edu.supporter.biz.order.dao;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.santu.edu.supporter.biz.order.dao.mapper.OrderMapper;
import com.santu.edu.supporter.biz.order.pojo.dto.OrderDTO;
import com.santu.edu.supporter.biz.order.pojo.po.OrderPO;
import com.santu.edu.supporter.util.PageData;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luoyaoqi
 * @createTime 2024/3/18
 * @description
 */
@Repository
@RequiredArgsConstructor
public class OrderDao {

    private final OrderMapper orderMapper;

    public void addOrder(OrderDTO dto) {
        OrderPO item = OrderPO.createItem(dto);
        orderMapper.addOrder(item);
    }

    public void updateOrderAddress(String orderId, String addressId) {
        orderMapper.updateOrderAddress(orderId, addressId);
    }

    public void removeOrder(String orderId) {
        orderMapper.removeOrder(orderId);
    }

    public PageData<OrderDTO> getOrderList(String userId, Integer orderStatus, Integer page, Integer size) {
        Page<OrderPO> pageData = orderMapper.selectOrderPage(userId, orderStatus, new Page<>(page, size));
        List<OrderPO> recordList = pageData.getRecords();
        if (CollUtil.isEmpty(recordList)) {
            return new PageData<>(Collections.emptyList(), pageData.getPages(), pageData.getTotal());
        }
        List<OrderDTO> dtoList = recordList.stream().map(OrderDTO::createItem).collect(Collectors.toList());
        return new PageData<>(dtoList, pageData.getPages(), pageData.getTotal());
    }

    public void updateOrderStatus(String orderId, Integer newStatus, Integer oldStatus) {
        orderMapper.updateOrderStatus(orderId, newStatus, oldStatus);
    }

    public OrderDTO getOrderById(String orderId) {
        OrderPO item = orderMapper.selectOrderById(orderId);
        return OrderDTO.createItem(item);
    }
}
